package com.sgj.sync;

/**
 * @Author: Guoji Shen
 * @Date: 2021/8/4 15:07
 */
public class SaleTicket {

    public static void main(String[] args) {
        // 创建 Ticket 对象
        Ticket ticket = new Ticket();
        // 创建3个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 调用卖票方法
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "AA").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 调用卖票方法
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "BB").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 调用卖票方法
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "CC").start();
    }
}

class Ticket {

    /**
     * 票数
     */
    private int number = 30;

    /**
     * 操作方法：卖票
     */
    public synchronized void sale() {
        // 判断是否有票
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "  卖出：" + number-- + "张票  还剩：" + number + "张票！");
        } else {
            System.out.println("票卖完了！！");
        }
    }
}